package com.icss.ah.productPublish.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import net.sf.json.JSON;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.log4j.Logger;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.icss.ah.base.bean.SyncSelectTree;
import com.icss.ah.base.util.ResourceLoader;
import com.icss.ah.util.HttpClientUtil;
import com.icss.ah.util.HttpUtil;
import com.wx.util.WxFileUtil;

@Service
@Transactional
public class ProductPublishService {

	@Autowired
	private SqlSessionTemplate sqlSessionTemplate;

	private final Logger errlog = Logger.getLogger("E");
	private final Logger infolog = Logger.getLogger("I");

	// 提现接口服务
	private String unitUrl = ResourceLoader.getInstance("icss").getString("UNIT_INFO_URL");

	/**
	 * 商品类目列表查询
	 * 
	 * @return
	 */
	public List<Map<String, Object>> getCategoryList(Map<String, String> map) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = sqlSessionTemplate.selectList("ProductPublishBean.getCategoryList", map);
			infolog.info("ProductPublishService|getCategoryList|para:" + map);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|getCategoryList", e);
		}
		return list;
	}

	/**
	 * 类目搜索
	 * 
	 * @param map
	 * @return
	 */
	public List<Map<String, String>> getCategoryNameList(Map<String, String> map) {
		List<Map<String, String>> list = new ArrayList<Map<String, String>>();
		try {
			List<Map<String, Object>> infoList = sqlSessionTemplate.selectList("ProductPublishBean.getCategoryNameList",
					map);
			for (int i = 0; i < infoList.size(); i++) {
				Map<String, Object> info = infoList.get(i);
				String code = (String) info.get("categoryCode");
				String cascadeName = getCascadeName1(code);
				Map<String, String> m = new HashMap<String, String>();
				m.put("CATEGORY_CODE", code);
				m.put("itemName", cascadeName);
				list.add(m);
			}
			infolog.info("ProductPublishService|getCategoryNameList success");
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|updateProKey", e);
		}
		return list;
	}

	public String getCascadeName1(String val) {
		Map<String, Object> obj = proCategory(val);
		String pCode = (String) obj.get("CATEGORY_PCODE");
		if (null == pCode || "".equals(pCode)) {
			return (String) obj.get("CATEGORY_NAME");
		} else {
			return getCascadeName1(pCode) + ">" + (String) obj.get("CATEGORY_NAME");
		}
	}

	public Map<String, Object> proCategory(String val) {
		Map<String, Object> info = sqlSessionTemplate.selectOne("ProductPublishBean.proCategory", val);
		return info;
	}

	/**
	 * 商品销售区域查询
	 * 
	 * @param map
	 * @return
	 */
	public List<Map<String, Object>> queryShopAreaList(Map<String, String> map) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = sqlSessionTemplate.selectList("ProductPublishBean.queryProductAreaList", map);
			if (list.isEmpty())
				list = sqlSessionTemplate.selectList("ProductPublishBean.queryShopAreaList", map);
			infolog.info("ProductPublishService|queryShopAreaList|para:" + map);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|queryShopAreaList", e);
		}
		return list;
	}

	/**
	 * 商品参数
	 * 
	 * @param map
	 * @return
	 */
	public List<Map<String, Object>> getBaseParam(Map<String, String> map) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = sqlSessionTemplate.selectList("ProductPublishBean.getBaseParam", map);
			infolog.info("ProductPublishService|getBaseParam");
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|getBaseParam", e);
		}
		return list;
	}

	/**
	 * 字典查询
	 * 
	 * @param map
	 * @return
	 */
	public List<Map<String, Object>> getDirectoryInfo(Map<String, String> map) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = sqlSessionTemplate.selectList("ProductPublishBean.getDirectoryInfo", map);
			infolog.info("ProductPublishService|getDirectoryInfo");
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|getDirectoryInfo", e);
		}
		return list;
	}

	/**
	 * 计量单位查询
	 * 
	 * @param map
	 * @return
	 */
	public List<Map<String, Object>> getMeasuringInfo() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = sqlSessionTemplate.selectList("ProductPublishBean.getMeasuringInfo");
			infolog.info("ProductPublishService|getMeasuringInfo");
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|getMeasuringInfo", e);
		}
		return list;
	}

	/**
	 * 计量单位查询-new
	 * 
	 * @param map
	 * @return
	 */
	public List<Map<String, Object>> queryUnitInfo(Map<String, String> map) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = sqlSessionTemplate.selectList("ProductPublishBean.queryUnitInfo", map);
			infolog.info("ProductPublishService|queryUnitInfo");
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|queryUnitInfo", e);
		}
		return list;
	}

	public List<SyncSelectTree> getTree(Map<String, String> map) {
		// SyncSelectTree selectTree
		// String id = selectTree.getId();//id 异步加载展开树时传到后台的id
		// String ifAll = selectTree.getIfAll();//是否一次性展示所有数据，1是 0否
		List<SyncSelectTree> list = new ArrayList<SyncSelectTree>();
		try {
			// if (ifAll != null && !"".equals(ifAll)) {
			// if ("0".equals(ifAll)) {//展开树时加载数据
			// if ("".equals(id)) {//如果查询id没有值，表示查询根节点
			// list =
			// sqlSessionTemplate.selectList("ProductPublishBean.getTree",selectTree);
			// }else{//如果查询id与入口编码编码不相等，表示查询根节点下的子节点
			// list =
			// sqlSessionTemplate.selectList("ProductPublishBean.getTreeChild",selectTree);
			// }
			// }else{//一次加载所有数据
			// if ("".equals(id)) {//如果查询id没有值，表示查询根节点
			// list =
			// sqlSessionTemplate.selectList("ProductPublishBean.getTreeAll",selectTree);
			// }else{//如果查询id与入口编码编码不相等，表示查询根节点下的子节点
			// list =
			// sqlSessionTemplate.selectList("ProductPublishBean.getTreeChild",selectTree);
			// }
			// }
			// }

			///// 取店铺销售区域
			List<Map<String, Object>> areaList = sqlSessionTemplate.selectList("ProductPublishBean.getShopArea", map);
			Set<String> set = new HashSet<String>();
			if (areaList != null && !areaList.isEmpty()) {
				for (int i = 0; i < areaList.size(); i++) {
					Map<String, Object> obj = areaList.get(i);
					String areaCode = (String) obj.get("AREA_CODE");
					set.add(areaCode);
					set.add(areaCode.substring(0, 9));
					set.add(areaCode.substring(0, 6));
					set.add(areaCode.substring(0, 3));
				}
			}
			String areaStr = "'0'";
			for (String code : set) {
				areaStr += ",'" + code + "'";
			}
			// areaStr = areaStr.substring(2);
			map.put("areaStr", areaStr);
			////////

			list = sqlSessionTemplate.selectList("ProductPublishBean.getTreeAll", map);
			infolog.info("ProductPublishService|getTree|list:" + list);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|getTree", e);
		}
		return list == null ? new ArrayList<SyncSelectTree>() : list;
	}

	/**
	 * 品牌查询
	 */
	public List<Map<String, Object>> queryBrandInfoList(HashMap<String, String> map) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = sqlSessionTemplate.selectList("ProductPublishBean.queryBrandCodeList", map);
			infolog.info("ProductPublishService|queryBrandInfoList|list" + list);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|queryBrandInfoList", e);
		}
		return list;
	}

	/**
	 * 保存商品基本信息
	 * 
	 * @param map
	 * @return
	 */
	public boolean saveTwo(Map<String, String> map, List<Map<String, String>> listPara,
			List<Map<String, String>> listKey, List<Map<String, String>> areaList) {
		boolean result = false;
		try {

			Integer count = sqlSessionTemplate.selectOne("ProductPublishBean.getProductCount", map);

			sqlSessionTemplate.update("ProductPublishBean.updateProductAuditStatus", map);
			infolog.info("ProductPublishService|updateProductAuditStatus|para:" + map);
			if (count > 0) {
				sqlSessionTemplate.update("ProductPublishBean.updateProductInfo", map);
				infolog.info("ProductPublishService|updateProductInfo|para:" + map);
			} else {
				// sqlSessionTemplate.delete("ProductPublishBean.delProductInfo",map);

				// 新增商品信息
				sqlSessionTemplate.insert("ProductPublishBean.insertProduct", map);
				infolog.info("ProductPublishService|insertProduct|para:" + map);
			}
			if (!listPara.isEmpty()) {
				// 保存商品参数
				sqlSessionTemplate.delete("ProductPublishBean.delProParam", map);
				sqlSessionTemplate.insert("ProductPublishBean.insertProPara", listPara);
				infolog.info("ProductPublishService|insertProPara|list:" + listPara);
			}
			if (!listKey.isEmpty()) {
				// 保存商品关键字
				sqlSessionTemplate.delete("ProductPublishBean.delProKey", map);
				sqlSessionTemplate.insert("ProductPublishBean.insertProKey", listKey);
				infolog.info("ProductPublishService|insertProKey|list:" + listKey);
			}
			// 新增商品投放区域
			sqlSessionTemplate.delete("ProductPublishBean.delProductArea", map);
			if (areaList.isEmpty()) {
				sqlSessionTemplate.insert("ProductPublishBean.insertProductArea", map);
				infolog.info("ProductPublishService|insertProductArea|para:" + map);
			} else {
				sqlSessionTemplate.insert("ProductPublishBean.insertProductAreaList", areaList);
				infolog.info("ProductPublishService|insertProductAreaList|list:" + areaList);
			}
			result = true;
			infolog.info("ProductPublishService|saveTwo success");
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|saveTwo", e);
		}
		return result;
	}

	public boolean saveThr(Map<String, String> map, List<Map<String, String>> listImg) {
		boolean result = false;
		try {
			// 完善商品信息
			sqlSessionTemplate.update("ProductPublishBean.updateProduct", map);
			infolog.info("ProductPublishService|updateProduct|para:" + map);

			sqlSessionTemplate.delete("ProductPublishBean.delProPic", map);
			if (!listImg.isEmpty()) {
				// 保存商品图片
				sqlSessionTemplate.insert("ProductPublishBean.insertProPic", listImg);
				infolog.info("ProductPublishService|insertProPic|para:" + listImg);
			}

			result = true;
			infolog.info("ProductPublishService|saveThr success");
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|saveThr", e);
		}
		return result;
	}

	/**
	 * 保存商品交易信息
	 * 
	 * @param map
	 * @return
	 */
	public boolean saveFour(Map<String, String> map, List<Map<String, String>> listBuy) {
		boolean result = false;
		try {
			Map<String, Object> info = sqlSessionTemplate.selectOne("ProductPublishBean.getProInfo", map);
			String typeCode = (String) info.get("typeCode");
			Map<String, String> para = new HashMap<String, String>();
			para.put("uuid", UUID.randomUUID().toString());
			para.put("productId", map.get("productId"));
			para.put("corpId", map.get("corpId"));
			para.put("shopId", map.get("shopId"));
			para.put("productTypeCode", map.get("typeCode"));
			if ("".equals(typeCode)) {
				sqlSessionTemplate.insert("ProductPublishBean.saveProductType", para);
			} else {
				Map<String, Object> o = sqlSessionTemplate.selectOne("ProductPublishBean.queryProductType", para);
				if (null == o)
					sqlSessionTemplate.insert("ProductPublishBean.saveProductType", para);
			}
			// 获取订购类型
			getProType(map, info);

			// 完善商品信息
			sqlSessionTemplate.update("ProductPublishBean.updateProInfo", map);
			infolog.info("ProductPublishService|updateProInfo|para:" + map);

			// 新增商品购进信息
			sqlSessionTemplate.delete("ProductPublishBean.delProBuy", map);
			map.put("uuid", UUID.randomUUID().toString());
			sqlSessionTemplate.insert("ProductPublishBean.insertProductBuy", map);

			// 新增商品审核信息
			sqlSessionTemplate.delete("ProductPublishBean.delProAudit", map);
			sqlSessionTemplate.insert("ProductPublishBean.insertProductAudit", map);
			if (!listBuy.isEmpty()) {
				// 保存商品价格
				sqlSessionTemplate.delete("ProductPublishBean.delProPrice", map);
				sqlSessionTemplate.insert("ProductPublishBean.insertProPrice", listBuy);
				infolog.info("ProductPublishService|insertProPrice|list:" + listBuy);
			}

			result = true;
			infolog.info("ProductPublishService|saveFour success");
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|saveFour", e);
		}
		return result;
	}

	private void getProType(Map<String, String> map, Map<String, Object> info) {
		try {
			// 订购类型 ,针对001
			String categoryCode = (String) info.get("categoryCode");
			if (categoryCode.indexOf("001") == 0) {
				String proUnitCode = (String) info.get("proUnitCode");
				int proType = 4;
				switch (proUnitCode) {
				// 月订
				case "YD": {
					proType = 4;
					break;
				}
				// 季订
				case "JDD": {
					proType = 3;
					break;
				}
				// 半年订
				case "BND": {
					proType = 2;
					break;
				}
				// 年订
				case "QND": {
					proType = 1;
					break;
				}
				default: {
					break;
				}
				}
				map.put("proType", String.valueOf(proType));
			}
		} catch (Exception e) {
			errlog.error("ProductPublishService|proType", e);
			map.put("proType", "4");
		}
	}

	/**
	 * 店铺类别
	 * 
	 * @param map
	 * @return
	 */
	public List<Map<String, Object>> getShopType(Map<String, String> map) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = sqlSessionTemplate.selectList("ProductPublishBean.getShopType", map);
			infolog.info("ProductPublishService|getShopType|para:" + map);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|getShopType", e);
		}
		return list;
	}

	/**
	 * 查询商品信息
	 * 
	 * @param map
	 * @return
	 */
	public Map<String, Object> getProInfo(Map<String, String> map) {
		Map<String, Object> info = new HashMap<String, Object>();
		try {
			info = sqlSessionTemplate.selectOne("ProductPublishBean.getProInfo", map);
			infolog.info("ProductPublishService|getProInfo|para:" + map);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|getProInfo", e);
		}
		return info;
	}

	public String getCascadeName(String val) {
		Map<String, Object> obj = proCategory(val);
		if (obj == null)
			return "";
		String pCode = (String) obj.get("CATEGORY_PCODE");
		if (null == pCode || "".equals(pCode)) {
			return (String) obj.get("CATEGORY_NAME");
		} else {
			return getCascadeName(pCode) + ">>" + (String) obj.get("CATEGORY_NAME");
		}
	}

	/**
	 * 复制
	 * 
	 * @param map
	 * @return
	 */
	public boolean copyProduct(HashMap<String, String> map) {
		boolean result = false;
		try {
			sqlSessionTemplate.update("ProductPublishBean.copyProduct", map);
			result = true;
			infolog.info("ProductPublishService|copyProduct|para:" + map);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|copyProduct", e);
		}
		return result;
	}

	/**
	 * 查询审核信息
	 * 
	 * @param uuid
	 * @return
	 */
	public Map<String, Object> getAuditInfo(String uuid) {
		Map<String, Object> info = new HashMap<String, Object>();
		try {
			info = sqlSessionTemplate.selectOne("ProductPublishBean.getAuditInfo", uuid);
			infolog.info("ProductPublishService|getAuditInfo|para" + uuid);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|getAuditInfo", e);
		}
		return info;
	}

	/**
	 * 查询商品关键字
	 * 
	 * @param map
	 * @return
	 */
	public List<Map<String, Object>> getKeyWord(Map<String, String> map) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = sqlSessionTemplate.selectList("ProductPublishBean.getKeyWord", map);
			infolog.info("ProductPublishService|getKeyWord|para:" + map);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|getKeyWord", e);
		}
		return list;
	}

	/**
	 * 查询商品参数
	 * 
	 * @param map
	 * @return
	 */
	public List<Map<String, Object>> getProParam(Map<String, String> map) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = sqlSessionTemplate.selectList("ProductPublishBean.getProParam", map);
			infolog.info("ProductPublishService|getProParam|para:" + map);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|getProParam", e);
		}
		return list;
	}

	/**
	 * 查询商品图片
	 * 
	 * @param map
	 * @return
	 */
	public List<Map<String, Object>> getProPic(Map<String, String> map) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = sqlSessionTemplate.selectList("ProductPublishBean.getProPic", map);
			infolog.info("ProductPublishService|getProPic|para:" + map);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|getProPic", e);
		}
		return list;
	}

	/**
	 * 查询商品价格
	 * 
	 * @param map
	 * @return
	 */
	public List<Map<String, Object>> getProPrice(Map<String, String> map) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = sqlSessionTemplate.selectList("ProductPublishBean.getProPrice", map);
			infolog.info("ProductPublishService|getProPrice|para:" + map);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|getProPrice", e);
		}
		return list;
	}

	public List<Map<String, Object>> queryUnfinishedProList(Map<String, String> map) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = sqlSessionTemplate.selectList("ProductPublishBean.queryUnfinishedProList", map);
			infolog.info("ProductPublishService|queryUnfinishedProList|para:" + map);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|queryUnfinishedProList", e);
		}
		return list;
	}

	public Long queryUnfinishedProListCount(Map<String, String> map) {
		Long total = 0l;
		try {
			total = sqlSessionTemplate.selectOne("ProductPublishBean.queryUnfinishedProListCount", map);
			infolog.info("ProductPublishService|queryUnfinishedProListCount|para:" + map);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|queryUnfinishedProListCount", e);
		}
		return total;
	}

	public List<Map<String, Object>> queryTemplateInfo(Map<String, String> map) {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = sqlSessionTemplate.selectList("ProductPublishBean.queryTemplateInfo", map);
			infolog.info("ProductPublishService|queryTemplateInfo|para:" + map);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|queryTemplateInfo", e);
		}
		return list;
	}

	/**
	 * 删除商品信息
	 * 
	 * @param map
	 * @return
	 */
	public String delInfo(Map<String, String> map) {
		String result = "f";
		try {
			// sqlSessionTemplate.delete("ProductPublishBean.delProParam",map);
			// sqlSessionTemplate.delete("ProductPublishBean.delProKey",map);
			// sqlSessionTemplate.delete("ProductPublishBean.delProductArea",map);
			// sqlSessionTemplate.delete("ProductPublishBean.delProPic",map);
			// sqlSessionTemplate.delete("ProductPublishBean.delProPrice",map);
			// sqlSessionTemplate.delete("ProductPublishBean.delProAudit",map);
			// sqlSessionTemplate.delete("ProductPublishBean.delInfo",map);
			sqlSessionTemplate.update("ProductPublishBean.upInfo", map);
			result = "t";
			infolog.info("ProductPublishService|delInfo|para:" + map);
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|delInfo", e);
		}
		return result;
	}

	public JSONArray getUnitInfo(Map<String, String> map) {
		JSONArray arr = new JSONArray();
		try {
			unitUrl += "productData/getProductInfo.do";
			String postData = com.alibaba.fastjson.JSON.toJSONString(map);
			String resultStr = HttpClientUtil.postData(unitUrl, postData, "UTF-8");
			System.out.println(unitUrl + "======" + map + "===resultJson===" + resultStr);
			infolog.info("ProductPublishService|getUnitInfo|resultStr:" + resultStr);
			if (resultStr != null) {
				JSONObject json = JSONObject.fromObject(resultStr);
				String rows = json.optString("rows");
				if (rows != null)
					arr = JSONArray.fromObject(rows);
			}
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|getUnitInfo", e);
		}
		return arr;
	}

	public String setUnitInfo(Map<String, String> map) {
		String result = "2";
		try {
			unitUrl += "productData/setProductInfo.do";
			List<Map<String, String>> list = new ArrayList<Map<String, String>>();
			list.add(map);
			Map<String, List<Map<String, String>>> obj = new HashMap<String, List<Map<String, String>>>();
			obj.put("rows", list);
			String postData = com.alibaba.fastjson.JSON.toJSONString(obj);
			String resultStr = HttpClientUtil.postData(unitUrl, postData, "UTF-8");
			System.out.println(unitUrl + "======" + map + "===resultJson===" + resultStr);
			infolog.info("ProductPublishService|setUnitInfo|resultStr:" + resultStr);
			if (resultStr != null) {
				JSONObject json = JSONObject.fromObject(resultStr);
				result = json.optString("result");
			}
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|setUnitInfo", e);
		}
		return result;
	}

	public List<Map<String, Object>> queryUnitList() {
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		try {
			list = sqlSessionTemplate.selectList("ProductPublishBean.queryUnitList");
			infolog.info("ProductPublishService|queryUnitList|list:" + list.size());
		} catch (Exception e) {
			e.printStackTrace();
			errlog.error("ProductPublishService|queryUnitList", e);
		}
		return list;
	}

}
